//
//  YXBrokenView.m
//  BrokenLine
//
//  Created by Rookie_YX on 16/10/19.
//  Copyright © 2016年 Rookie_YX. All rights reserved.
//

#import "YXBrokenView.h"

@interface YXBrokenView ()<CAAnimationDelegate>
@property (nonatomic, strong) CAShapeLayer *lineCharLayer;
@property (nonatomic, strong) UIBezierPath *pathOne;
/** 渐变背景视图*/
@property (nonatomic, strong) UIView *gradientBackground;
/** 渐变图层*/
@property (nonatomic, strong) CAGradientLayer *gradientLayer;
/** 颜色数组*/
@property (nonatomic, strong) NSMutableArray *gradientLayerColorsArrr;

@end

@implementation YXBrokenView

static CGFloat boundceX = 20;
static CGFloat boundceY = 20;

- (instancetype)initWithFrame:(CGRect)frame dataArr:(NSArray *)dataArray brokenLineViewYMaxNum:(NSUInteger)Y{
  if (self = [super initWithFrame:frame]) {
    self.backgroundColor = [UIColor whiteColor];
    self.dataArray = dataArray;
    self.maxY = Y;
    [self createLabelX];
    [self createLabelY];
    [self drawGradientBackgroundView];
    [self setLineDash];
    [self drawBrokenLine];
  }
  return self;
}
- (void)drawRect:(CGRect)rect {
  [super drawRect:rect];
  /*******画出坐标轴********/
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSetLineWidth(context, 2.0);
  CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
  CGContextMoveToPoint(context, boundceX, boundceY);
  CGContextAddLineToPoint(context, boundceX, rect.size.height - boundceY);
  CGContextAddLineToPoint(context,rect.size.width -  boundceX, rect.size.height - boundceY);
  CGContextStrokePath(context);
}

#pragma mark - private methond

// 画横轴数据
- (void)createLabelX{
  CGFloat month  = self.dataArray.count;
  for (NSInteger i = 0; i < month; i++) {
    CGFloat X = (self.frame.size.width - 2*boundceX)/month*i + boundceX;
    CGFloat Y = self.frame.size.height - boundceY + boundceY *0.3 + 3;
    CGFloat width = (self.frame.size.width - 2*boundceX)/month ;
    CGFloat hight = boundceY / 2;
    UILabel *labelMonth = [[UILabel alloc] initWithFrame:CGRectMake(X, Y, width, hight)];
    labelMonth.tag = 1000 + i;
    labelMonth.text = [NSString stringWithFormat:@"%ld月",i + 1];
    labelMonth.font = [UIFont systemFontOfSize:10];
    labelMonth.transform = CGAffineTransformMakeRotation(M_PI*0.3);
    [self addSubview:labelMonth];
  }
}

// 画纵轴数据
- (void)createLabelY{
  CGFloat Ydivision = self.maxY;
  for (NSInteger i = 0; i < Ydivision; i++) {
    UILabel * labelYdivision = [[UILabel alloc]initWithFrame:CGRectMake(0, (self.frame.size.height - 2 * boundceY)/Ydivision *i + boundceX , boundceY, boundceY/2.0)];
    //   labelYdivision.backgroundColor = [UIColor greenColor];
    labelYdivision.tag = 2000 + i;
    labelYdivision.text = [NSString stringWithFormat:@"%.0f",(Ydivision - i)*100];
    labelYdivision.font = [UIFont systemFontOfSize:10];
    [self addSubview:labelYdivision];
  }
}

// 画渐变颜色
- (void)drawGradientBackgroundView{
  // 渐变背景视图（不包含坐标轴）
  self.gradientBackground = [[UIView alloc] initWithFrame:CGRectMake(boundceX, boundceY, self.bounds.size.width - boundceX*2, self.bounds.size.height - 2*boundceY)];
  [self addSubview:self.gradientBackground];
  /** 创建并设置渐变背景图层 */
  //初始化CAGradientlayer对象，使它的大小为渐变背景视图的大小
  self.gradientLayer = [CAGradientLayer layer];
  self.gradientLayer.frame = self.gradientBackground.bounds;
  //设置渐变区域的起始和终止位置（范围为0-1），即渐变路径
  self.gradientLayer.startPoint = CGPointMake(0, 0.0);
  self.gradientLayer.endPoint = CGPointMake(1.0, 0.0);
  //设置颜色的渐变过程
  self.gradientLayerColorsArrr = [NSMutableArray arrayWithArray:@[(__bridge id)[UIColor colorWithRed:23 / 255.0 green:146/ 255.0 blue:79 / 255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:19 / 255.0 green:135/ 255.0 blue:65 / 255.0 alpha:1.0].CGColor]];
  self.gradientLayer.colors = self.gradientLayerColorsArrr;
  //将CAGradientlayer对象添加在我们要设置背景色的视图的layer层
  [self.gradientBackground.layer addSublayer:self.gradientLayer];
}

// 添加虚线
- (void)setLineDash{
  
  for (NSInteger i = 0;i < self.maxY; i++ ) {
    CAShapeLayer * dashLayer = [CAShapeLayer layer];
    dashLayer.strokeColor = [UIColor whiteColor].CGColor;
    dashLayer.fillColor = [[UIColor clearColor] CGColor];
    // 默认设置路径宽度为0，使其在起始状态下不显示
    dashLayer.lineWidth = 1.0;
    // 虚线点数组
    dashLayer.lineDashPattern=[NSArray arrayWithObjects:[NSNumber numberWithInt:1],
                               [NSNumber numberWithInt:(int)self.maxY],nil];
    
    UILabel * label1 = (UILabel*)[self viewWithTag:2000 + i];
    UIBezierPath * path = [[UIBezierPath alloc]init];
    path.lineWidth = 1.0;
    UIColor * color = [UIColor blueColor];
    
    [color set];
    [path moveToPoint:CGPointMake( 0, label1.frame.origin.y - boundceY)];
    [path addLineToPoint:CGPointMake(self.frame.size.width - 2*boundceX,label1.frame.origin.y - boundceY)];
    CGFloat dash[] = {10,10};
    [path setLineDash:dash count:2 phase:10];
    [path stroke];
    dashLayer.path = path.CGPath;
    [self.gradientBackground.layer addSublayer:dashLayer];
  }
}

// 画折线图
- (void)drawBrokenLine{
  
  UILabel * label = (UILabel*)[self viewWithTag:1000];
  UIBezierPath * path = [[UIBezierPath alloc]init];
  path.lineWidth = 1.0;
  self.pathOne = path;
  UIColor * color = [UIColor greenColor];
  [color set];
  for (NSUInteger i = 0; i < self.dataArray.count; i++) {
    [path moveToPoint:CGPointMake( label.frame.origin.x - boundceX, (600 - [self.dataArray[i]  doubleValue]) /600.0 * (self.frame.size.height - boundceY*2 )  )];
  }
  //创建折现点标记
  for (NSInteger i = 1; i< self.dataArray.count; i++) {
    UILabel * label1 = (UILabel*)[self viewWithTag:1000 + i];
    CGFloat  arc = [self.dataArray[i] doubleValue];
    [path addLineToPoint:CGPointMake(label1.frame.origin.x - boundceX,  (600 -arc) /600.0 * (self.frame.size.height - boundceY*2 ) )];
    UILabel * falglabel = [[UILabel alloc]initWithFrame:CGRectMake(label1.frame.origin.x , (600 -arc) /600.0 * (self.frame.size.height - boundceY*2 )+ boundceY  , 30, 15)];
    //  falglabel.backgroundColor = [UIColor blueColor];
    falglabel.tag = 3000+ i;
    falglabel.text = [NSString stringWithFormat:@"%.1f",arc];
    falglabel.font = [UIFont systemFontOfSize:8.0];
    [self addSubview:falglabel];
  }
  // [path stroke];
  
  self.lineCharLayer = [CAShapeLayer layer];
  self.lineCharLayer.path = path.CGPath;
  self.lineCharLayer.strokeColor = [UIColor whiteColor].CGColor;
  self.lineCharLayer.fillColor = [[UIColor clearColor] CGColor];
  // 默认设置路径宽度为0，使其在起始状态下不显示
  self.lineCharLayer.lineWidth = 0;
  self.lineCharLayer.lineCap = kCALineCapRound;
  self.lineCharLayer.lineJoin = kCALineJoinRound;
  
  [self.gradientBackground.layer addSublayer:self.lineCharLayer];//直接添加导视图上
  //   self.gradientBackgroundView.layer.mask = self.lineChartLayer;//添加到渐变图层
  
  // 链接各点绘制折线
  self.lineCharLayer.lineWidth = 2;
  CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
  pathAnimation.duration = 3;
  pathAnimation.repeatCount = 1;
  pathAnimation.removedOnCompletion = YES;
  pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
  pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
//  // 设置动画代理，动画结束时添加一个标签，显示折线终点的信息
//  pathAnimation.delegate = self;
  [self.lineCharLayer addAnimation:pathAnimation forKey:@"strokeEnd"];

}

#pragma mark - getting
- (NSArray *)dataArray{
  if (!_dataArray) {
    _dataArray = [NSArray new];
  }
  return _dataArray;
}

@end
